<template>
    <div>
        <el-tabs v-model="activeName" @tab-click="handleClick" class="version-com">
            <el-tab-pane label="正常版本" name="first">
                <el-card class="operate-container" shadow="never">
                    <div>
                        <el-button size="mini" class="btn-add" @click="handleAdd()" >添加新版本</el-button>
                        <el-button size="mini" class="btn-add" @click="handlePublsh()" >发布现行版本</el-button>
                    </div>
                    <span class="btn-list" @click="refBtn">刷新列表</span>
                </el-card>
                <div class="table-container">
                    <el-table ref="firstTable"
                                :data="list"
                                style="width: 100%;"
                                v-loading="listLoading" border>
                        <el-table-column label="版本号" align="center">
                            <template slot-scope="scope">
                                <span style="display: inline-block;width: 60px;">{{scope.row.version}}</span>
                                <span v-if="scope.row.status === 'PUBLISH'" style="color: green;">{{ dealStatus(scope.row.status) }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="发布时间" align="center">
                            <template slot-scope="scope">{{scope.row.updateTime | formatDateTime}}</template>
                        </el-table-column>
                        <el-table-column label="创建时间" align="center">
                            <template slot-scope="scope">{{scope.row.createTime | formatDateTime}}</template>
                        </el-table-column>
                        <el-table-column align="center">
                            <template slot="header">
                                发布软件强提示
                                <el-tooltip class="item" effect="dark" content="打开app进入首页时弹出，1天1次，持续5天" placement="top">
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </template>
                            <template slot-scope="scope">{{scope.row.forceUpgrade ? '是': '否'}}</template>
                        </el-table-column>
                        <el-table-column label="APK附件" align="center">
                            <template slot-scope="scope">
                                <!-- <el-button size="mini"
                                        type="text"
                                        @click="handleApk(scope.$index, scope.row)">{{scope.row.apkName}}
                                </el-button> -->
                                <a :href="scope.row.apkUrl" style="color: #66b1ff;">{{scope.row.apkName}}</a>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="360" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                        type="text"
                                        v-if="!scope.row.active"
                                        @click="handleEdite(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        v-if="!scope.row.active"
                                        @click="handleDown(scope.$index, scope.row)">过低
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        v-if="!scope.row.active"
                                        @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                                <span v-if="scope.row.active">编辑</span>
                                <span v-if="scope.row.active">过低</span>
                                <span v-if="scope.row.active">删除</span>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination-container">
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        layout="total, sizes,prev, pager, next,jumper"
                        :current-page.sync="listQuery.pageNum"
                        :page-size="listQuery.pageSize"
                        :page-sizes="[10,15,20]"
                        :total="total">
                    </el-pagination>
                </div>
            </el-tab-pane>
            <el-tab-pane label="过低版本" name="second">
                <el-card class="operate-container" shadow="never">
                    <div></div>
                    <span class="btn-list" @click="refBtn">刷新列表</span>
                </el-card>
                <div class="table-container">
                    <el-table ref="secondTable"
                                :data="list"
                                style="width: 100%;"
                                v-loading="listLoading" border>
                        <el-table-column align="center">
                            <template slot="header">
                                过低版本号
                                <el-tooltip class="item" effect="dark" content="检测用户版本属于过低版本的，打开app进入首页时弹出，每次打开app都弹，直到用户更新" placement="top">
                                    <i class="el-icon-question"></i>
                                </el-tooltip>
                            </template>
                            <template slot-scope="scope">{{scope.row.version}}</template>
                        </el-table-column>
                        <el-table-column label="发布时间" align="center">
                            <template slot-scope="scope">{{scope.row.updateTime | formatDateTime}}</template>
                        </el-table-column>
                        <el-table-column label="创建时间" align="center">
                            <template slot-scope="scope">{{scope.row.createTime | formatDateTime}}</template>
                        </el-table-column>

                        <el-table-column label="APK附件" align="center">
                            <template slot-scope="scope">
                                <!-- <el-button size="mini"
                                        type="text"
                                        @click="handleApk(scope.$index, scope.row)">{{scope.row.apkName}}
                                </el-button> -->
                                <a :href="scope.row.apkUrl" style="color: #66b1ff;">{{scope.row.apkName}}</a>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="360" align="center">
                            <template slot-scope="scope">
                                <el-button size="mini"
                                        type="text"
                                        @click="handleRemove(scope.$index, scope.row)">移除过低
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleEdite(scope.$index, scope.row)">编辑
                                </el-button>
                                <el-button size="mini"
                                        type="text"
                                        @click="handleDelete(scope.$index, scope.row)">删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
                <div class="pagination-container">
                    <el-pagination
                        background
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        layout="total, sizes,prev, pager, next,jumper"
                        :current-page.sync="listQuery.pageNum"
                        :page-size="listQuery.pageSize"
                        :page-sizes="[10,15,20]"
                        :total="total">
                    </el-pagination>
                </div>
            </el-tab-pane>
        </el-tabs>

        <el-dialog
            title="添加/编辑软件版本"
            :visible.sync="dialogVisible"
            width="75%">
            <el-form :model="addList"
                    :rules="rules"
                    ref="addForm"
                    label-width="180px" size="small"  class="demo-ruleForm">
                <el-form-item label="版本号：" prop="version">
                    <el-input v-model="addList.version" style="width: 250px"></el-input>
                </el-form-item>
                <el-form-item label="上传apk：" prop="apkUrl">
                    <!-- <el-input v-model="addList.apkUrl" style="width: 0"></el-input> -->
                    <el-upload
                        ref="uploadFileList"
                        action=""
                        class="upload-demo"
                        style="display:inline-block;max-width: 670px;"
                        :limit="1"
                        multiple
                        list-type="text"
                        accept=".apk"
                        :before-upload="beforeUpload"
                    >
                        <el-button slot="trigger" size="small" type="primary" :disabled="fileBtnDisabled">选取文件</el-button>
                    </el-upload>
                    *仅支持扩展名：.apk
                    <span>{{ temp.fileName }}</span>
                </el-form-item>
                <!-- <el-form-item label="" prop="" label-width="105px">
                    <el-progress
                        :percentage="progressPercent"
                    ></el-progress>
                </el-form-item> -->
                <el-form-item label="弹窗介绍内容（繁体中文）: " prop="descZhHk" label-width="105px">
                    <EditorHK :height="300" v-model="addList.descZhHk"></EditorHK>
                </el-form-item>
                <el-form-item label="弹窗介绍内容（简体中文）: " prop="descZhCn" label-width="105px">
                    <Editor :height="300" v-model="addList.descZhCn"></Editor>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer" style="display: flex;justify-content: end;align-items: center;padding-right: 50px;">
                <div class="is-force">
                    <el-checkbox v-model="addList.forceUpgrade" @change="changeBox"></el-checkbox>
                    <span>发布时是否强提示</span>
                    <i class="el-icon-question"></i>
                </div>
                <el-button @click="dialogVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handleDialogConfirm('addForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            title="发布现行版本"
            :visible.sync="publishVisible"
            width="40%">
            <el-form :model="publishList"
                    ref="publishForm"
                    label-width="180px" size="small">
                <el-form-item label="选择版本：">
                    <el-select v-model="publishId" placeholder="请选择版本号">
                        <el-option
                            v-for="item in choiceList"
                            :key="item.id"
                            :label="item.version"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="生效时间：">
                    <span>立即生效</span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="publishVisible = false" size="small">取 消</el-button>
                <el-button type="primary" @click="handlePublishConfirm('publishForm')" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { versionList, versionAdd, versionDelete, fileUploading, versionUnder, versionUpdate, versionPublish, fetchAllResourceList } from "@/api/app";
import Editor from '@/components/Editor';
import EditorHK from '@/components/EditorHK';
import {formatDate} from '@/utils/date';
const defaultListQuery = {
    pageNum: 1,
    pageSize: 80,
    version: null,
    under: false
};
const defaultAdd = {
    id: null,
    platform: null,
    version: null,
    descZhHk: null,
    descZhCn: null,
    apkName: null,
    apkUrl: null,
    active: null,
    forceUpgrade: true,
    under: null,

};
const defaultPublish = {
    id: null,
    version: null,
}

export default {
    name: 'versionsManage',
    components: {
        Editor,
        EditorHK,
    },
    data() {
        return {
            listQuery: Object.assign({}, defaultListQuery),
            addList: Object.assign({}, defaultAdd),
            publishList: Object.assign({}, defaultPublish),
            activeName: 'first',
            dialogVisible: false,
            publishVisible: false,
            list: null,
            total: null,
            listLoading: false,
            rules: {
                version: [
                    { required: true, message: '请填写版本号' }
                ],
                apkUrl: [
                    { required: true, message: '请上传apk' }
                ],
                descZhHk: [
                    { required: true, message: '请填写弹窗介绍内容（繁体中文）' }
                ],
                descZhCn: [
                    { required: true, message: '请填写弹窗介绍内容（简体中文）' }
                ],
            },
            isValid: false,
            choiceList: [],
            fileBtnDisabled: false, // 文件上传按钮是否禁用
            temp: {},
            progressPercent: 0,
            loading: false,
            publishId: null,
            choiceRow: null,
            isAdd: true,
            btnMenu: {
                edit: true,
                delete: true,
            },
        }
    },
    created() {
        const menu = JSON.parse(localStorage.getItem('listMenu'));
        const item = menu.filter(item => item.title === '软件版本管理')[0];
        fetchAllResourceList({menuId: item.id }).then(res => {
            res.data.forEach(dom => {
            if (dom.component === '' && dom.name === '后台角色管理') {
                this.btnMenu.edit = false;
            }
            if (dom.component === '' && dom.name === '后台角色删除') {
                this.btnMenu.delete = false;
            }
            });
        });
        this.getList();
    },
    filters: {
        formatDateTime(time) {
          if (time == null || time === '') {
            return '-';
          }
          let date = new Date(time);
          return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
        }
    },
    watch: {
        // isValid(val) {
        //     console.log('1111', val);
        // },
    },
    methods: {
        refBtn() {
            this.getList();
        },
        dealStatus(type) {
            let word = null;
            switch(type) {
                case 'UN_PUBLISH':
                    word = '未发布';
                    break;
                case 'PUBLISH':
                    word = '已发布';
                    break;
                case 'CANCEL':
                    word = '已取消';
                    break;
                default: break;
            }
            return word;
        },
        handleClick(tab, event) {
            if (tab.name === 'first') {
                this.listQuery.under = false;
            } else {
                this.listQuery.under = true;
            }
            this.getList();
        },
        handleAdd() {
            this.addList = {
                id: null,
                platform: null,
                version: null,
                descZhHk: null,
                descZhCn: null,
                apkName: null,
                apkUrl: null,
                active: null,
                forceUpgrade: true,
                under: null,
            };
            this.isAdd = true;
            this.dialogVisible = true;
        },
        handlePublsh() {
            this.publishVisible = true;
        },
        getList() {
            this.listLoading = true;
            versionList(this.listQuery).then(response => {
                // console.log(response);
                this.listLoading = false;
                this.list = response.data.records;
                this.total = response.data.total;
                this.choiceList = this.list.filter((item) => {
                    return item.status !== 'PUBLISH';
                })
                // console.log(this.list, this.choiceList);
            });
        },
        handleSizeChange(val) {
            this.listQuery.pageNum = 1;
            // this.listQuery.pageSize = val;
            this.getList();
        },
        handleCurrentChange(val) {
            this.listQuery.pageNum = val;
            this.getList();
        },
        handleApk(index, row) {
            // console.log(index, row);
            // window.href = row.apkUrl;
            const down = document.createElement('a');
            down.href = row.apkUrl;
            down.download = 'file.apk';
            document.body.appendChild(down);
            down.click();
            document.body.removeChild(down);
        },
        handleEdite(index, row) {
            // console.log(index, row);
            this.choiceRow = row;
            this.addList = row;
            console.log(this.addList);
            this.isAdd = false;
            this.dialogVisible = true;
        },
        handleTwoEdite(index, row) {
            console.log(index, row);
        },
        handleDown(index, row) {
            // console.log(index, row);
            this.$confirm('确定要过低该版本吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                versionUnder({id: row.id, under: true}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '移出成功!'
                    });
                    this.getList();
                });
            });
        },
        handleRemove(index, row) {
            // console.log(index, row);
            this.$confirm('确定移出该低版本吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                versionUnder({id: row.id, under: false}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '移出成功!'
                    });
                    this.getList();
                });
            });
        },
        handleDelete(index, row) {
            this.$confirm('是否要删除该版本?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                versionDelete({id: row.id, content: row.content}).then(response => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getList();
                });
            });
        },
        changeBox(e) {
            if (!e) {
                this.$confirm('你确定要取消强提示吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                }, () => {
                    this.addList.forceUpgrade = true;
                });
            }
        },
        handleDialogConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    if (this.isAdd) {
                        versionAdd(this.addList).then(res => {
                            this.$message({
                                type: 'success',
                                message: '新增成功!'
                            });
                            this.dialogVisible = false;
                            this.getList();
                        })
                    } else {
                        versionUpdate(this.addList).then(res => {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                            this.dialogVisible = false;
                            this.getList();
                        })
                    }
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        handlePublishConfirm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    versionPublish({id: this.publishId}).then(res => {
                        this.getList();
                        this.publishVisible = false;
                    })
                } else {
                    return false;
                }
            });
        },
        beforeUpload(file) {
            // console.log('file', file)
            // 验证
            if (file.size === 0) {
                this.$notify({
                    title: '失败',
                    message: '不存在上传文件',
                    type: 'error',
                    duration: 2000
                })
                // this.$message({
                //     type: 'success',
                //     message: '删除成功!'
                // });
                return false
            }
            // console.log(1111, file)
            this.loading = true
            const from = new FormData();
            from.append('file', file);
            from.append('type', 1);
            this.progress = true // 显示进度条
            this.temp.fileName = file.name // 文件名称置空
            this.progressPercent = 0 // 进度条百分比
            const uploadEvent = (progressEvent) => { // 进度条百分比
                this.progressPercent = Number(
                ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)
                );
            };
            // this.source = this.connectionSource() // 中断请求时用
            // const cacheToken = this.source.token  // 这个是上传会话token，取消上传操作需要的参数
            this.fileBtnDisabled = true // 禁用上传按钮
            /**
             * 上传文件接口
             */
            // console.log('上传文件', from, uploadEvent);
            fileUploading(from).then(res => {
                // 请求成功后，将文件名称，路径，大小复制到temp对应字段中，新增修改要用
                this.temp = Object.assign({}, this.temp, {
                    fileName: file.name,
                    url: res.data,
                    size: file.size
                })
                this.addList.apkName = file.name;
                this.addList.apkUrl = res.data;
                // console.log(res, this.temp);
                this.$notify({
                    title: '成功',
                    message: '请求成功',
                    type: 'success',
                    duration: 2000
                })
                this.progress = false // 隐藏进度条
                this.loading = false
                this.fileBtnDisabled = false // 启用上传按钮
            }).catch(() => {
                this.progress = false // 隐藏进度条
                this.loading = false
                this.fileBtnDisabled = false // 启用上传按钮
            })
            return false
        },
    }
}
</script>

<style lang="scss" scoped>
.version-com {
    margin: 20px;
}
.is-force {
    margin-right: 10px;
    color: #3e3e3e;
    font-size: 14px;
}
.btn-list {
    cursor: pointer;
}
</style>
